package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private WorkspaceService workspaceService;
    /**统计指定时间内的营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getturnoverStatistics(LocalDate begin, LocalDate end) {
        //用于存放从begin到end 范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //将dateList 集合中的每个元素取出来，使用 , 分隔
        String time = StringUtils.join(dateList, ",");

        //存放每天的营业额
        List<Double> list = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询Date 日期对应的营业数据。即状态为已完成的订单金额合计
            //select sum(amount) from orders where order_time >
            //某一天的开始时间 --》 00：00:00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //某一天的结束时间 --》 23:59:59:999999
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            //当天的营业额
            Double tunover = orderMapper.sumByMap(map);
            //如果当天营业额为空，则将营业额置为0
            tunover  = tunover == null ? 0.0 : tunover;

            list.add(tunover);


        }
        String turnoverlist = StringUtils.join(list, ",");


        return TurnoverReportVO
                .builder()
                .dateList(time)
                .turnoverList(turnoverlist)
                .build();
    }

    /**用户数据统计
     *
     * @param begin
     * @param end
     * @return
     */

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //用于存放从begin到end 范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //将dateList 集合中的每个元素取出来，使用 , 分隔
        String time = StringUtils.join(dateList, ",");
        //每天新增用户数量
        List<Integer> newUserList = new ArrayList<>();
        //每天的总用户数量
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            //先查总数量
            map.put("end",endTime);
            Integer totaluser = userMapper.countByMap(map);
            totaluser =  totaluser == null ? 0 : totaluser;
            //再查新增数量
            map.put("begin",beginTime);
            Integer newuser =  userMapper.countByMap(map);
            newuser =  newuser == null ? 0 : newuser;
            //分别放入对应的集合中
            totalUserList.add(totaluser);
            newUserList.add(newuser);
        }
        String totalUser = StringUtils.join(totalUserList, ",");
        String newUser = StringUtils.join(newUserList, ",");
        return UserReportVO.builder()
                .dateList(time)
                .totalUserList(totalUser)
                .newUserList(newUser)
                .build();

        
    }

    /**
     * 订单数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天的日期
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //将dateList 集合中的每个元素取出来，使用 , 分隔
        String time = StringUtils.join(dateList, ",");

        //存放每天的订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天的有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        //查询每天的有效订单数和总订单数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //查询每天的订单总数
            Integer orderCount = getOrderCount(beginTime, endTime, null);

            //查询每天都有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);


            orderCountList.add(orderCount);

            validOrderCountList.add(validOrderCount);

        }

        //计算时间区间内的订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //计算时间区间内的有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成概率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount !=0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;

        }

        return OrderReportVO.builder()
                .dateList(time)
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }
    /**
     * 根据条件统计订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.countByMap(map);

    }

    /**
     * 销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //获得所有的name 放入list集合
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        // 获得所有的number 放入list集合
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**数据导出
     *
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) throws Exception {
        //查询数据库，获取营业数据。最近30天的数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessDataVO = workspaceService.getToday(LocalDateTime.of(dateBegin, LocalTime.MIN)
                , LocalDateTime.of(dateEnd, LocalTime.MAX));
        //通过poi将数据写入excel文件

        FileInputStream fileInputStream = new FileInputStream(new File("sky-server/src/main/resources/template/运营数据报表模板.xlsm"));
        //InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsm");
        try {
            //基于模板文件创建一个新的文件
            XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
            //填充数据 -- 时间段
            //获取sheet标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //、获取行、单元格、写入数据
            sheet.getRow(1).getCell(1)
                     .setCellValue("时间: "+dateBegin+"----"+dateEnd);

            //获取第四行
            XSSFRow row = sheet.getRow(3);
            //填充营业额
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //填充订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //填充新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获取第五行
            row = sheet.getRow(4);
            //填充有效订单数
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //填充平均客单价
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            /*
            * 明细数据填充
            * */

            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询到某一天的营业数据
                BusinessDataVO todayBusinessData = workspaceService.getToday(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(7 + i);

                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(todayBusinessData.getTurnover());
                row.getCell(3).setCellValue(todayBusinessData.getValidOrderCount());
                row.getCell(4).setCellValue(todayBusinessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(todayBusinessData.getUnitPrice());
                row.getCell(6).setCellValue(todayBusinessData.getNewUsers());


            }

            //通过输出流将excel文件下载到浏览器（）
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            fileInputStream.close();
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



        //通过输出流将excel文件下载到浏览器（）



    }


}
